<template>
  <div class="extended_fields div_screen2">
    <div v-if="disabled" class="disabledMask"></div>
    <template v-for="(item, index) in tableData">
      <div class="custom_item" v-if="item.visibility">
        <div class="custom_star">
          <div class="custom_label" style="width: auto; min-width: 50px">{{ item.fieldName }}</div>
        </div>
        <div class="custom_select_head">
          <template v-if="item.fieldType === 'datePicker'">
            <change-date-time-picker v-model="item.fieldValue" :initVlue="item.fieldValue"></change-date-time-picker>
          </template>
          <template v-else-if="item.fieldType.includes('select')">
            <!-- <el-select
              v-model="item.fieldValue"
              :placeholder="item.placeholder"
              :multiple="item.fieldType === 'selectMultiple'"
              collapse-tags
              :collapse-tags-tooltip="true"
            >
              <el-option
                v-for="option in item.fieldOptionsFacade"
                :key="option.option"
                :label="option.option"
                :value="option.option"
              ></el-option>
            </el-select> -->
            <a-select
              class="custom-select"
              v-model="item.fieldValue"
              :mode="item.fieldType === 'selectMultiple' ? 'multiple' : 'default'"
              style="width: 190px"
              :allowClear="true"
              :maxTagCount="1"
              :maxTagTextLength="3"
              :showArrow="true"
              :options="handleOptions(item.fieldOptionsFacade)"
            ></a-select>
          </template>
          <template v-else>
            <el-input class="custom_input" v-model="item.fieldValue"></el-input>
          </template>
        </div>
      </div>
    </template>
    <el-button
      v-if="!disabled"
      class="custom_item"
      type="text"
      icon="el-icon-edit"
      @click="openDialog"
      style="color: #1a93fa; padding: 0; font-size: 12px"
    >
      单据扩展属性设置
    </el-button>
    <el-dialog
      title="单据扩展属性设置"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form ref="tableForm" :model="{ tableDataCopy }">
        <el-table
          :data="tableDataCopy"
          style="width: 100%; border: 1px solid #eee; border-bottom: 0"
          :header-cell-style="{ background: '#eee', color: '#666' }"
        >
          <el-table-column prop="index" label="序号" align="center" width="100">
            <template slot-scope="scope">
              <div class="index-cell">
                <el-tooltip content="上移" placement="top" :enterable="false">
                  <el-button type="text" class="move-btn" @click="moveUp(scope.row.sort)">
                    <i class="el-icon-top"></i>
                  </el-button>
                </el-tooltip>

                <span class="index-number">{{ scope.row.sort.toString().padStart(2, '0') }}</span>
                <!-- <span class="index-number">{{ (scope.$index + 1).toString().padStart(2, '0') }}</span> -->

                <el-tooltip content="下移" placement="top" :enterable="false">
                  <el-button type="text" class="move-btn" @click="moveDown(scope.row.sort)">
                    <i class="el-icon-bottom"></i>
                  </el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="自定义名称" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="`tableDataCopy.${scope.$index}.fieldName`"
                :rules="[
                  {
                    required: scope.row.visibility,
                    message: '请输入自定义名称',
                    trigger: 'blur',
                  },
                ]"
                style="margin-bottom: 0"
              >
                <el-input
                  v-model="scope.row.fieldName"
                  placeholder="请输入自定义名称"
                  maxlength="20"
                  size="mini"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="输入项" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="`tableDataCopy.${scope.$index}.fieldType`"
                :rules="[
                  {
                    required: scope.row.visibility,
                    message: '请选择输入项类型',
                    trigger: 'change',
                  },
                ]"
                style="margin-bottom: 0"
              >
                <el-select v-model="scope.row.fieldType" placeholder="请选择" @change="handleChange(scope.row)">
                  <el-option label="选项-单选" value="select"></el-option>
                  <el-option label="选项-多选" value="selectMultiple"></el-option>
                  <el-option label="输入框" value="input"></el-option>
                  <el-option label="日期时间" value="datePicker"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="setUp" label="" width="150">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center">
                <el-button
                  v-if="['select', 'selectMultiple'].includes(scope.row.fieldType)"
                  type="text"
                  size="small"
                  @click="setUp(scope.row)"
                  style="color: #1a93fa; padding: 0; font-size: 15px; margin-right: 15px"
                  >设置</el-button
                >
                <el-switch v-model="scope.row.visibility"></el-switch>
                <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.$index)">
                  <el-button slot="reference" type="text" class="delete-btn">
                    <i class="el-icon-close" style="font-size: 16px"></i>
                  </el-button>
                </el-popconfirm>
                <edit-options ref="editOptions" :rowData="scope.row" @saveOptions="saveOptions"></edit-options>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetDefault">还原默认值</el-button>
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button size="small" @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ChangeDateTimePicker from './changeDate-time-picker.vue'
import EditOptions from './editOptions.vue'
import { getAction, postAction } from '@/api/manage'
import { message } from 'ant-design-vue/es'
import Vue from 'vue'
import { ACCOUNT_BOOK } from '@/store/mutation-types'
import { any } from 'joi'
export default {
  name: 'ExtendedFields',
  components: {
    ChangeDateTimePicker,
    EditOptions,
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      defaultTableData: [
        { sort: 1, fieldName: '', fieldType: '', visibility: false, fieldOptionsFacade: [], fieldValue: '' },
        { sort: 2, fieldName: '', fieldType: '', visibility: false, fieldOptionsFacade: [], fieldValue: '' },
        { sort: 3, fieldName: '', fieldType: '', visibility: false, fieldOptionsFacade: [], fieldValue: '' },
        { sort: 4, fieldName: '', fieldType: '', visibility: false, fieldOptionsFacade: [], fieldValue: '' },
        { sort: 5, fieldName: '', fieldType: '', visibility: false, fieldOptionsFacade: [], fieldValue: '' },
      ],
      dialogVisible: false,
      tableData: [],
      accountBookId: '',
      hasFData: false,
      newOrder: true,
      select: '',
      tableDataCopy: [],
      isData:false,
      saveUrl:'/xghOrderExtendField/xghOrderExtendField/add'
    }
  },
  watch:{
    tableData:{
      handler(newVal){
        // console.log(newVal,'--- watch newVal')
      },
      deep:true
    }
  },
  created() {
    this.accountBookId = Vue.ls.get(ACCOUNT_BOOK) && Vue.ls.get(ACCOUNT_BOOK).id
    console.log(this.accountBookId, '---accountBookId')
    this.initTableData()
  },
  methods: {
    handleOptions(options) {
      if (!options) {
        return []
      }
      return options.map((item) => ({
        label: item.option,
        value: item.option,
      }))
    },
    handleChange(row) {
      // 如果是多选类型，fieldValue需要设置为空数组类型，不能为空字符串，否则会有一个空白选项
      if (row.fieldType === 'selectMultiple') {
        row.fieldValue = []
      }
    },
    openDialog() {
      this.dialogVisible = true
      this.tableDataCopy = JSON.parse(JSON.stringify(this.tableData))
    },
    // 处理表格数据
    handleData(data) {
      if (data.length < 5) {
        // 复制新值
        let updatedData = [...data]
        // 计算需要补充的数量
        const needToAdd = 5 - data.length
        // 使用默认值补齐到5条
        for (let i = data.length; i < data.length + needToAdd; i++) {
          updatedData.push({
            sort: i + 1,
            fieldName: '',
            fieldType: '',
            visibility: false,
            fieldOptionsFacade: [],
            fieldValue: '',
          })
        }
        // this.$set(this, 'tableData', updatedData)
        console.log(updatedData,'---handledata')
        return updatedData
      }
      console.log(data,'---handledata')
      return data
    },
    // 初始化表格数据
    initTableData() {
      this.tableData = JSON.parse(JSON.stringify(this.defaultTableData))
      // 获取单据扩展属性设置
      getAction('/xghOrderExtendField/xghOrderExtendField/list', {
        accountBookId: this.accountBookId,
        orderType: 1,
      }).then((res) => {
        // 处理扩展字段多选时的选项，将字符串转换为数组
        res.result.forEach((item) => {
          if (item.fieldType === 'selectMultiple' && typeof item.fieldValue === 'string' && item.fieldValue) {
            console.log(item.fieldValue, '---item.fieldValue','转成数组')
            item.fieldValue = item.fieldValue.split(',')
          }
        })
        this.tableData = this.handleData(res.result)
        const limitedResult = res.result.slice(0, 5);
        for (let i = 0; i < limitedResult.length; i++) {
          const item = limitedResult[i];
          if (item.fieldType || item.fieldName) {
            this.isData = true;
            this.saveUrl = '/xghOrderExtendField/xghOrderExtendField/edit';
            break;
          }
        }
        console.log('isData:', this.isData);
        // 更新父组件的tableData，用于解决没有点开扩展数据时，提交保存接口extendFields没有数据
        // this.$emit('updateData', this.tableData)
      })
    },
    handleCancel() {
      this.dialogVisible = false
      this.tableDataCopy = [...this.defaultTableData]
    },
    // 关闭弹窗
    handleClose(done) {
      console.log('handleClose')
      this.dialogVisible = false
      // this.initTableData()
      this.tableDataCopy = [...this.defaultTableData]
      done()
    },
    // 更新表格数据，父组件调用
    updateTableData(data) {
      // 处理扩展字段多选时的选项，将字符串转换为数组
      if (Array.isArray(data)) {
        data.forEach((item) => {
          // 如果是多选类型且 fieldValue 是字符串，则转换为数组
          if (item.fieldType === 'selectMultiple' && typeof item.fieldValue === 'string' && item.fieldValue) {
            item.fieldValue = item.fieldValue.split(',')
          }
        })
      }

      if (data === 'new') {
        this.newOrder = true
        this.initTableData()
        return
      }
      this.newOrder = false
      this.$set(this, 'tableData', this.handleData(data))
      console.log(this.tableData, '---获取了父组件传来的单据扩展属性')
    },
    // 上移
    moveUp(sort) {
      // 找到当前行的数组索引
      const currentIndex = this.tableDataCopy.findIndex((item) => item.sort === sort)
      if (currentIndex > 0) {
        // 保存当前行和上一行的数据
        const currentRow = { ...this.tableDataCopy[currentIndex] }
        const prevRow = { ...this.tableDataCopy[currentIndex - 1] }

        // 交换 sort 值
        const tempSort = currentRow.sort
        currentRow.sort = prevRow.sort
        prevRow.sort = tempSort

        // 更新数组
        this.$set(this.tableDataCopy, currentIndex - 1, currentRow)
        this.$set(this.tableDataCopy, currentIndex, prevRow)
      }
    },
    // 下移
    moveDown(sort) {
      // 找到当前行的数组索引
      const currentIndex = this.tableDataCopy.findIndex((item) => item.sort === sort)
      if (currentIndex < this.tableDataCopy.length - 1) {
        // 保存当前行和下一行的数据
        const currentRow = { ...this.tableDataCopy[currentIndex] }
        const nextRow = { ...this.tableDataCopy[currentIndex + 1] }

        // 交换 sort 值
        const tempSort = currentRow.sort
        currentRow.sort = nextRow.sort
        nextRow.sort = tempSort

        // 更新数组
        this.$set(this.tableDataCopy, currentIndex + 1, currentRow)
        this.$set(this.tableDataCopy, currentIndex, nextRow)
      }
    },
    // 点击设置选项
    setUp(row) {
      this.$refs.editOptions.openDialog(row)
    },
    // 重置默认值
    resetDefault() {
      this.$confirm({
        content: '确定要还原默认值吗？',
        centered: true,
        onOk: () => {
          // this.initTableData()
          // this.tableData = JSON.parse(JSON.stringify(this.defaultTableData))

          // 重置为默认值
          // 保存原有数据的id
          const originalIds = this.tableDataCopy.map((item) => item.id)

          // 重置为默认值
          this.tableDataCopy = JSON.parse(JSON.stringify(this.defaultTableData))

          // 恢复原有的id
          this.tableDataCopy.forEach((item, index) => {
            if (originalIds[index]) {
              item.id = originalIds[index]
            }
          })

          this.save()
          message.success('已还原默认值')
        },
      })
    },
    // 保存
    save() {
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          // 保存时，若不是选项类型，则清空选项数据
          this.tableDataCopy.forEach((item, index) => {
            if (!['select', 'selectMultiple'].includes(item.fieldType)) {
              item.fieldOptionsFacade = []
            }
          })
          this.tableData = JSON.parse(JSON.stringify(this.tableDataCopy))
          console.log(this.tableData,'---save 时的tabledata')
          // 如果不是新建单据，则直接返回
          if (!this.newOrder) {
            // this.$emit('updateData', this.tableData)
            this.dialogVisible = false
            return
          }
          // 如果是新建单据，则保存
          // 如果初始化数据为空则添加add否则edit
          postAction(this.saveUrl, {
            extendFields: this.tableData,
            accountBookId: this.accountBookId,
            orderType: 1,
          }).then((res) => {
            const limitedResult = this.tableData.slice(0, 5);
            let hasData = false; // 用于标记是否有数据
            // 遍历前 5 条数据
            for (let i = 0; i < limitedResult.length; i++) {
                const item = limitedResult[i];
                if (item.fieldType || item.fieldName) {
                    hasData = true;
                    break;
                }
            }

            // 根据遍历结果更新 isData 和 saveUrl
            if (hasData) {
                this.isData = true;
                this.saveUrl = '/xghOrderExtendField/xghOrderExtendField/edit';
            } else {
                this.isData = false;
                this.saveUrl = '/xghOrderExtendField/xghOrderExtendField/add';
            }
            console.log('isData:', this.isData);
            // this.$emit('updateData', this.tableData)
            this.dialogVisible = false
          })
        }
      })
    },
    // 删除
    handleDelete(sort) {
      const id = this.tableDataCopy[sort].id || ''
      this.$set(this.tableDataCopy, sort, {
        id: id,
        sort: ++sort + '',
        fieldName: '',
        fieldType: '',
        visibility: false,
        fieldOptionsFacade: [],
        fieldValue: '',
      })
    },
    // 设置弹框内 点击保存选项
    saveOptions(row) {
      this.$set(this.tableDataCopy, row.sort - 1, row)
    },
    // 获取表格数据
    getTableData() {
      return this.tableData
    },
  },
}
</script>
<style lang="scss">
// 添加全局样式(不要使用 scoped)
.ant-modal-wrap {
  z-index: 3000 !important;
}
</style>
<style lang="scss" scoped>
.disabledMask {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
}
.extended_fields {
  position: relative;
  display: flex;
  justify-content: flex-start !important;
  min-height: 40px;
  flex-wrap: wrap;
  .dialog-footer {
    display: flex;
    justify-content: center;
  }

  ::v-deep .el-date-editor {
    height: 32px !important;
    .el-input__inner {
      height: 32px !important;
    }
  }
  .custom_label {
    width: max-content !important;
  }
  .custom_input {
    :deep(.el-input__inner) {
      height: 32px !important;
      width: 190px !important;
    }
  }
  .el-input--mini {
    :deep(.el-input__inner) {
      height: 32px !important;
    }
  }
  // 删除按钮默认隐藏
  .delete-btn {
    visibility: hidden;
    padding: 0;
    color: #f56c6c;
    margin-left: 20px;
  }
  :deep(.el-table) {
    .index-cell {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .index-number {
        margin: 0 8px;
      }

      .move-btn {
        visibility: hidden;
        padding: 0;
        color: #409eff;

        &:hover {
          color: #66b1ff;
        }

        i {
          font-size: 18px;
          font-weight: bold;
        }
      }
    }

    // hover 时显示删除按钮
    tr:hover {
      .delete-btn {
        visibility: visible;
      }
      .move-btn {
        visibility: visible;
      }
    }
  }
}
:deep(.el-table__cell) {
  padding: 0 10px !important;
  .cell {
    padding: 15px 0 !important;
  }
  .el-form-item__error {
    padding-top: 1px;
  }
  .el-select {
    line-height: 32px;
  }
}
.div_screen2 {
      width: 100%;
      // heig ht: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      ::v-deep .el-select {
        height: 30px;
        box-sizing: border-box;
        margin-right: 10px;

        .el-input {
          height: 100%;

          .el-input__inner {
            height: 100%;
            font-size: 12px;
          }

          .el-input__suffix {
            height: 100%;
            display: flex;
            align-items: center;
          }

          .el-textarea {
            height: 100%;
            width: 30px;
          }
        }
      }

      ::v-deep .el-date-editor {
        width: 120px;
        height: 30px;

        .el-input__inner {
          width: 100%;
          height: 30px;
          padding: 0 0.187512rem;
          font-size: 12px;
          color: #666;
        }

        .el-input__prefix {
          left: unset;
          right: 5px;

          .el-input__icon {
            line-height: 30px;
            font-size: 16px;
          }
        }

        .el-input__suffix {
          display: none;
        }
      }

      .screen_right {
        width: 30px;
        height: 30px;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;

        .set_up {
          line-height: 20px;
          font-size: 20px;
          color: rgb(153, 153, 153);
        }
      }
    }
</style>
